package com.shuoyue.adven.init;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.shuoyue.adven.entity.AppVersionInfo;
import com.shuoyue.adven.entity.PowerTimePlan;
import com.shuoyue.adven.network.RetrofitClient;
import com.sm.appbase.base.basemvp.BaseModel;
import com.sm.appbase.base.basemvp.BasePresenter;
import com.sm.appbase.base.basemvp.BaseView;
import com.sm.appbase.net.base.ApiSubscriber;
import com.sm.appbase.net.base.BaseResult;
import com.sm.appbase.net.base.Optional;
import com.sm.appbase.net.exception.NetErrorException;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VersionContract {

    public interface View extends BaseView {
        void downloadSuc(File f);

        void getVersion(AppVersionInfo appVersionInfo);

        void progress(int progress);

        void downloadStart();

        void downloadError(String msg);

        void setPowerInfo(List<PowerTimePlan> planList);
    }

    public static class Presenter extends BasePresenter<View> {
        Model model = new Model();

        public void getVersionInfo() {
            apply(model.getVersionInfo()).subscribe(new ApiSubscriber<Optional<AppVersionInfo>>(mView, this) {
                @Override
                public void onNext(Optional<AppVersionInfo> appVersionInfoOptional) {
                    super.onNext(appVersionInfoOptional);
                    mView.getVersion(appVersionInfoOptional.getIncludeNull());
                }
            });
        }
        public void getPowerPlan(){
            apply(model.getPowerPlan()).subscribe(new ApiSubscriber<Optional<List<PowerTimePlan>>>(mView, this) {
                @Override
                public void onNext(Optional<List<PowerTimePlan>> appVersionInfoOptional) {
                    super.onNext(appVersionInfoOptional);
                    mView.setPowerInfo(appVersionInfoOptional.getIncludeNull());
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e); mView.setPowerInfo(null);
                }

                @Override
                protected void onFail(NetErrorException error) {
                    super.onFail(error); mView.setPowerInfo(null);
                }
            });
        }
        public void downloadApk(String url, String savePath) {
            File file = new File(savePath);
            if(file.exists()){
                file.delete();
            }
            model.downloadFile(url, new DownloadHelper.DownloadApkListener() {
                @Override
                public void onStart() {
                    Log.e("下载进度", "开始下载");
                    mView.downloadStart();
                }

                @Override
                public void onProgress(int p) {
                    Log.e("下载进度", "" + p);
                    mView.progress(p);

                }

                @Override
                public void onFinish(String path) {
                    File file = new File(path);
                    if (file.exists()) {
                        mView.downloadSuc(file);
                    }
                }

                @Override
                public void onError(String msg) {
                    Log.e("下载错误", msg);
                    mView.downloadError(msg);
                }
            }, savePath);
        }
    }

    public static class Model extends BaseModel {
        public Observable<BaseResult<AppVersionInfo>> getVersionInfo() {
            return RetrofitClient.getInstance().getApi().checkVersion();
        }

        public void downloadFile(String url, final DownloadHelper.DownloadApkListener downloadApkListener, String savePath) {
            RetrofitClient.getInstance().getDownloadService().downloadFileUrl(url).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        new Thread(new DownloadHelper.FileDownloadRun(response, downloadApkListener, savePath)).start();
                    } else {
                        downloadApkListener.onError("连接超时");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    downloadApkListener.onError(t.getMessage());
                }

            });


        }

        public  Observable<BaseResult<List<PowerTimePlan>>>  getPowerPlan(){
            return RetrofitClient.getInstance().getApi().getPowerPlan();
        }
    }

    public static int packageCode(Context mContext) {
        PackageManager manager = mContext.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

}
